/*************************************************************
 * File: User.java
 * Copyright (c) 2012
 * Author: Huang Shaobin
 * Email: Shaobin.Software@gmail.com Shaobin_Software@163.com 
 * Date: Feb 3, 2013
 * Description: 
 ************************************************************/

package snow.biz.system.model;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;

import snow.biz.base.model.BaseEntity;
import snow.biz.security.model.Role;
import snow.core.enums.Status;

/**
 * @author Shaobin.Software@gmail.com Shaobin_Software@163.com
 * @version 1.0
 */
public class User extends BaseEntity<Integer> {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3130324960257945150L;

	private Group group; // 所属集团
	private String loginName; // 登录名称
	private String loginPass; // 登录密码
	private Map<Role, BaseEntity<Integer>> roles;

	protected User() {
		super();
	}

	public User(User createUser, Status status, Group group, String loginName, String loginPass, Collection<Role> roles) {
		super(createUser, status);
		this.group = group;
		this.loginName = loginName;
		setLoginPass(loginPass);
		if (CollectionUtils.isNotEmpty(roles)) {
			for (final Role role : roles) {
				addRole(createUser, role);
			}
		}
	}

	public synchronized boolean addRole(User currentUser, Role role) {
		if (!validEntity(currentUser) || !validEntity(role)) {
			return false;
		}
		if (this.roles == null) {
			this.roles = new HashMap<Role, BaseEntity<Integer>>();
		}
		if (this.roles.containsKey(role)) {
			return false;
		}
		this.roles.put(role, new BaseEntity<Integer>(currentUser, Status.SUCCESS));
		return true;
	}

	public Group getGroup() {
		return this.group;
	}

	public String getLoginName() {
		return this.loginName;
	}

	public String getLoginPass() {
		return this.loginPass;
	}

	public List<Role> getRoles() {
		if (MapUtils.isNotEmpty(this.roles)) {
			return new ArrayList<Role>(this.roles.keySet());
		}
		return Collections.emptyList();
	}

	public void setLoginPass(String loginPass) {
		this.loginPass = loginPass;
	}
}
